package com.da.javalog.check.processor;

import com.da.javalog.check.CheckRule;
import com.da.javalog.check.core.CheckBean;
import com.da.javalog.check.core.Checker;
import com.da.javalog.check.core.CheckerRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author joker
 * @date 2020/04/28
 */
@Component
@Slf4j
public class CheckBeanPostProcessor implements BeanPostProcessor {
    /**
     * Bean 实例化之前进行的处理
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * Bean 实例化之后进行的处理
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Checker) {
            CheckBean checkBean = bean.getClass().getAnnotation(CheckBean.class);
            // fix NPE
            if (checkBean == null) {
                return bean;
            }
            CheckRule checkRule = checkBean.rule();
            CheckerRegister.putChecker(checkRule, (Checker)bean);
        }
        return bean;
    }
}